<template>
	<a-modal :maskClosable="false" :title="info && info.id ? '编辑活动' : '新建活动'" :width="840" :visible="showModal"
		:confirm-loading="confirmLoading" :ok-type="'primary'" @ok="confirmOk" @cancel="cancel">
		<a-form :form="form">
			<section class="p-10 pl-24 mb-20" style="background: #f0f0f0;">
			  基础信息
			</section>
			<div class="pr-24">
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="渠道" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-select show-search    @search="searchData" class="flex-1" allow-clear placeholder="请选择渠道" v-decorator="['channelId', { rules: [{ required: true, message: '请选择渠道'}] }]">
								<a-select-option v-for="item in channelData" :key="item.id"
									:value="item.id">{{ item.name }}</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="活动码" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input placeholder="请输入活动码" :max-length="100"
								v-decorator="['code', { rules: [{ required: true, message: '请输入活动码', whitespace: true }] }]"></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="活动名称" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input placeholder="请输入活动名称" :max-length="100" v-decorator="[
				    'name',
				    { rules: [{ required: true, message: '请输入活动名称', whitespace: true }] },
				  ]"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15 flex-1" style="margin-left: 42px" label="是否启用" :label-col="{ span: 12 }"
							:wrapper-col="{ span: 12 }">
							<a-switch  checked-children="开" un-checked-children="关"
								v-decorator="['isEnabled', { valuePropName: 'checked' }]" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="[12, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="下单时间范围" :label-col="labelCol" :wrapper-col="wrapperCol">
							<!-- <a-input
				  placeholder="请输入活动名称"
				  :max-length="100"
				  v-decorator="[
				    'channelCallbackAddress',
				    { rules: [{ required: true, message: '请输入活动名称', whitespace: true }] },
				  ]"
				></a-input> -->
							<a-range-picker v-decorator="[
				    'orderTimeStart',
				    { rules: [{ required: true, message: '开始时间-结束时间' }] },
				  ]" class="w-full" placeholder="开始时间-结束时间" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="取车时间范围" :label-col="labelCol" :wrapper-col="wrapperCol">
							<!-- <a-input
				  placeholder="请输入活动名称"
				  :max-length="100"
				  v-decorator="[
				    'channelCallbackAddress',
				    { rules: [{ required: true, message: '请输入活动名称', whitespace: true }] },
				  ]"
				></a-input> -->
							<a-range-picker v-decorator="[
				    'pickupTimeStart',
				    { rules: [{ required: true, message: '开始时间-结束时间'}] },
				  ]" class="w-full" placeholder="开始时间-结束时间" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="还车时间范围" :label-col="labelCol" :wrapper-col="wrapperCol">
							<!-- <a-input
				  placeholder="请输入活动名称"
				  :max-length="100"
				  v-decorator="[
				    'channelCallbackAddress',
				    { rules: [{ required: true, message: '请输入活动名称', whitespace: true }] },
				  ]"
				></a-input> -->
							<a-range-picker v-decorator="[
				    'returnTimeStart',
				    { rules: [{ required: false, message: '开始时间-结束时间'}] },
				  ]" class="w-full" placeholder="开始时间-结束时间" />
						</a-form-item>
					</a-col>
				</a-row>
			</div>
			<section class="p-10 mb-20 pl-24" style="background: #f0f0f0;">
			 优惠信息(仅限租车费)
			</section>
			<div class="pr-24 pl-24">
				<a-row v-for="(item,index) in newList" :key="index" class="pt-20 mb-10"
					style="border: 1px solid #d9d9d9;position: relative;" :gutter="[0, 0]">
					<div @click="goDel(item,index)"
						style="position: absolute;right: 0;top: 9px;color: red;font-size: 24px;line-height: 0;">x</div>
						<a-col :span="12">
							<a-form-item class="mb-15" label="优惠类型" :label-col="labelCol" :wrapper-col="wrapperCol">
								<a-select @change="chooseDiscount($event,index)" placeholder="请选择优惠类型"
									v-decorator="[`couponType${index}`, { rules: [{ required: false, message: '请选择优惠类型' }] ,   initialValue: 4, }]">
									<a-select-option v-for="item in preferential" :key="item.value" :value="item.value">
										{{ item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="chooseDiscountIdx[index]==4">
							<a-form-item class="mb-15" label="减免租期(天)" :label-col="labelCol" :wrapper-col="wrapperCol">
								<a-input-number placeholder="请输入减免租期" :max="2147483647" :precision="0" class="w-full" :min="0"
									v-decorator="[`days${index}`, { rules: [{ required: true, message: '请输入减免租期' }] }]"></a-input-number>
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="chooseDiscountIdx[index]==2">
							<a-form-item class="mb-15" label="折扣比例（%）" :label-col="labelCol" :wrapper-col="wrapperCol">
								<a-input-number placeholder="例：90%等于九折" :max="2147483647" :precision="0" class="w-full" :min="1"
									v-decorator="[`ratio${index}`, { rules: [{ required: true, message: '折扣比例' }] }]"></a-input-number>
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="chooseDiscountIdx[index]==4||chooseDiscountIdx[index]==2">
							<a-form-item class="mb-15" label="最高优惠金额(元)" :label-col="labelCol" :wrapper-col="wrapperCol">
								<a-input-number placeholder="请输入最高优惠金额" :max="2147483647"  :precision="0" class="w-full" 
									v-decorator="[`maxCouponAmount${index}`, { rules: [{ required: false, message: '请输入最高优惠金额' }] }]"></a-input-number>
							</a-form-item>
						</a-col>
					<a-col :span="12" v-if="chooseDiscountIdx[index]==3">
						<a-form-item class="mb-15" label="减免金额(元)" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input-number placeholder="减免金额" :max="2147483647" :precision="0" class="w-full" 
								v-decorator="[`amount${index}`, { rules: [{ required: true, message: '请输入减免金额' }] }]"></a-input-number>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="最小租期(天)" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input-number placeholder="请输入最小租期" :max="2147483647" :precision="0" class="w-full" :min="0"
								v-decorator="[`minDays${index}`, { rules: [{ required: chooseDiscountIdx[index]==4?true:false, message: '请输入最小租期' }] }]"></a-input-number>
						</a-form-item>
					</a-col>
					
					
					<a-col :span="12" v-if="chooseDiscountIdx[index]==2||chooseDiscountIdx[index]==3||chooseDiscountIdx[index]==4">
						<a-form-item class="mb-15" label="满足金额(元)" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input-number placeholder="满足金额" :max="2147483647" :precision="0" class="w-full" 
								v-decorator="[`minAmount${index}`, { rules: [{ required: false, message: '请输入满足金额' }] }]"></a-input-number>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="下单有效周期" :label-col="labelCol" :wrapper-col="wrapperCol">
						   <a-select  mode="multiple"  v-decorator="[`week${index}`, { rules: [{ required: false, message: '请输入满足金额' }] }]" class="w-full" allow-clear placeholder="请选择下单有效周期">
						     <a-select-option v-for="item in orderCycle" :value="item.value" :key="item.value">{{
						       item.name
						     }}</a-select-option>
						   </a-select>
						</a-form-item>
					</a-col>
				</a-row>
			</div>
			<div  class="mt-10 ml-24" style="color: #1890ff;">
				<span @click="goAdd">添加优惠</span>
			</div>
		</a-form>
	</a-modal>
</template>

<script>
	import {
		createChannel,
		editChannel,
		getPageChannelList,getActivitytCreate,getActivityEdit,getChannelSerach
	} from '@/api/operationInfo/channel'
	import moment from 'moment'
	export default {
		props: {
			id: {
				type: Number,
				default: 0,
			},
		},
		data() {
			return {
				labelCol: {
					span: 8
				},
				wrapperCol: {
					span: 16
				},
				  channelData:[],//渠道
				showModal: false,
				orderCycle:[
					{
						name:'周一',
						value:1
					},
					{
						name:'周二',
						value:2
					},{
						name:'周三',
						value:3
					},
					{
						name:'周四',
						value:4
					},
					{
						name:'周五',
						value:5
					},
					{
						name:'周六',
						value:6
					},
					{
						name:'周日',
						value:0
					}
				],
				newList: [{
					minDays: 'minDays',
					couponType: 'couponType',
					minAmount: 'minAmount',
					week:'week',
					maxCouponAmount:'maxCouponAmount',
					days:'days'
				}],
				preferential:[
					// {
					// 	name:'未知',
					// 	value:0
					// },
					{
						name:'租免',
						value:4
					},
					{
						name:'折扣',
						value:2
					},
					{
						name:'立减',
						value:3
					}
				],
				confirmLoading: false,
				form: this.$form.createForm(this),
				fileList: [],
				info: null,
				searchTime: [],
				searchKey:'',
				chooseDiscountIdx:{
					// 0:1,
				},
			}
		},
		methods: {
			searchData(name){
				console.log(name)
			this.searchKey=name
			this.directConnections()
			},
			chooseDiscount(e,idx){//选择优惠点击事件
			this.$set(this.chooseDiscountIdx, idx, e);
			// this.[`chooseDiscountIdx${idx}`]=e
			console.log(this)
			console.log(e,'点击',this.chooseDiscountIdx)	
			},
			directConnections(){
				let obj={
					 isEnabled:true,
						isOnline:true,
					 search: this.searchKey.trim(),
					pageNum:1,
					rowsNum:30
				}
				getChannelSerach(obj).then((data) => {
				this.channelData = data.items
				})
			},
			codeValidator(rule, value, callback) {
				const amount = value && value.trim()
				const isCode = /^[a-zA-Z]+$/
				if (typeof amount === 'undefined') {
					callback(new Error('请输入渠道商编码'))
				}
				if (amount * 1 === 0 || (amount && !isCode.test(amount))) {
					callback(new Error('仅支持英文'))
				} else {
					callback()
				}
			},

			gettRends(name, index) {
				return `${name}${index}`
			},
			goAdd() {
				const initialData ={
					minDays: 'minDays',
					couponType: 'couponType',
					minAmount: 'minAmount',
					week:'week',
					maxCouponAmount:'maxCouponAmount',
					days:'days'
				}

				// 点击添加按钮时，将初始数据添加到 newList 数组中
				this.newList.push(initialData);
				// if(this.info){
				this.newList.forEach((res,idx)=>{
					this.chooseDiscountIdx[idx+this.newList.length-1]=4
				})	
				// }
			
			},
			goDel(item, index) {
				if (this.newList.length == 1) {
					this.$message.error('至少得保留一条优惠信息')
				} else {
					this.newList.splice(index, 1);
				}
			},
			confirmOk() {
 
				// startTime: this.$utils.getStartTime(this.searchTime[0]),
				// endTime: this.$utils.getEndTime(this.searchTime[1]),
				this.form.validateFields((err, values) => {
					console.log(values,'数据')
					const idx = this.newList.map((item, index) => index);

					const list = idx.map(i => ({
					  minDays: values[`minDays${i}`]==null?undefined:values[`minDays${i}`],
					  couponType: values[`couponType${i}`],
					  minAmount: values[`minAmount${i}`]==null?undefined:values[`minAmount${i}`],
					  week:values[`week${i}`]==null?undefined:values[`week${i}`],
					    ratio: values[`ratio${i}`]?values[`ratio${i}`]/100:values[`ratio${i}`],
						  amount: values[`amount${i}`]==null?undefined:values[`amount${i}`],
						  days:values[`days${i}`],
						    maxCouponAmount:values[`maxCouponAmount${i}`]==null?undefined:values[`maxCouponAmount${i}`],
					}))
					
                 let data={
					 preferentialInfo:list,
					 orderTimeStart:this.$utils.getStartTime(values.orderTimeStart[0]),
					  orderTimeEnd:this.$utils.getEndTime(values.orderTimeStart[1]),
					  pickupTimeStart:this.$utils.getStartTime(values.pickupTimeStart[0]),
					   pickupTimeEnd:this.$utils.getEndTime(values.pickupTimeStart[1]),
					   returnTimeStart:values.returnTimeStart?this.$utils.getStartTime(values.returnTimeStart[0]):'',
					   returnTimeEnd:values.returnTimeStart?this.$utils.getEndTime(values.returnTimeStart[1]):'',
						channelId:values.channelId,
						code:values.code,
						name:values.name,
						isEnabled: typeof values.isEnabled === 'undefined' ? true : values.isEnabled
				 }
				 if(this.info){
					data.id=this.info.id
				 }
				 console.log(values, data,'222',this.info)
               
					
					if (!err) {
						const {
							info
						} = this
						this.confirmLoading = true
						const fun = info && info.id ? getActivityEdit : getActivitytCreate
						fun(data)
							.then(() => {
								this.$message.success(info && info.id ? '编辑成功！' : '新建成功！')
								 this.$emit('getData')
								this.cancel()
							})
							.finally(() => {
								this.confirmLoading = false
							})
					}
				})
			},
		async createOrEditData(info) {
			this.chooseDiscountIdx={0:4}
			this.info=null
			console.log(this.info,'canshu')
			// searchTime: [moment(), moment().add(13, 'day')],
				// this.preferential = await this.$utils.getDictList('preferential')
			 this.directConnections()
				this.showModal = true
				if (info) {
				
					this.newList=[]
					this.info = info
					let data={
						channelId:info.channelId,
						code:info.code,
						name:info.name,
						isEnabled:info.isEnabled,
						orderTimeStart:[info.orderTimeStart,info.orderTimeEnd],
						pickupTimeStart:[info.pickupTimeStart,info.pickupTimeEnd],
						returnTimeStart:[info.returnTimeStart=='1970-01-01 00:00:00'||info.returnTimeStart=='0001-01-01 00:00:00'?undefined:info.returnTimeStart,info.returnTimeEnd=='1970-01-01 00:00:00'||info.returnTimeEnd=='0001-01-01 23:59:59'||info.returnTimeEnd=='0001-01-01 00:00:00'?undefined:info.returnTimeEnd],
						// channelId:info.info,
						// code:info.code,
						// channelId:info.info,
						// code:info.code,
						// channelId:info.info,
						// code:info.code
					}
					
					
					
					
					
					
					info.preferentialInfoDesc.forEach((res,idx)=>{
						this.newList.push(res)
						this.chooseDiscountIdx[idx]=res.couponType
						data[`minDays${idx}`]=res.minDays==0?undefined:res.minDays,
						data[`couponType${idx}`]=res.couponType,
						 data[`minAmount${idx}`]=res.minAmount==0?undefined:res.minAmount,
						 data[`week${idx}`]=res.week==null?undefined:res.week,
						 data[`maxCouponAmount${idx}`]=res.maxCouponAmount==0?undefined:res.maxCouponAmount,
						  data[`days${idx}`]=res.days==0?undefined:res.days,
						  data[`ratio${idx}`]=res.ratio*100,
												  data[`amount${idx}`]=res.amount==0?undefined:res.amount
					})
					console.log(this.chooseDiscountIdx,'xiabiao')
					console.log(data,'数据')
					this.$nextTick(() => {
						
						this.form.setFieldsValue({
							...data
						})
					})
					return false
				}
				this.$nextTick(() => {
					this.form.setFieldsValue({
						isEnabled: true
					})
				})
			},
			cancel() {
				this.newList=[{
					minDays: 'minDays',
					couponType: 'couponType',
					minAmount: 'minAmount',
					week:'week',
					maxCouponAmount:'maxCouponAmount',
					days:'days'
				}],
				this.fileList = []
				this.confirmLoading = false
				this.form.resetFields()
				this.showModal = false
			},
		},
	}
</script>

<style lang="less" scoped>
	/deep/.ant-modal-body{
		padding-left: 0;
		padding-right:0
		
	}
	.upload-list {
		/deep/ .ant-form-item-label {
			height: 30px;
			line-height: normal;
		}
	}
</style>